import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:management/utils/log_utils.dart';
import 'package:management/utils/channel.dart';
import 'package:management/views/visitor/checkIn/id-card-register-page.dart';
import 'package:management/utils/custom_router.dart';

///蓝牙界面
class BluetoothPage extends StatefulWidget {
  @override
  _BluetoothPageState createState() => _BluetoothPageState();
}

class _BluetoothPageState extends State<BluetoothPage> {
  ///蓝牙是否开启
  bool isOpen = false;

  /// 第一栏左边文字
  String openOrClose = "关闭";

  /// 第一栏背景颜色
  Color? openOrCloseBg = Colors.grey[700];

  /// 蓝牙可以被发现[couldBeFound] 默认为true
  /// TODO: 功能还未实现
  bool couldBeFound = true;

  ///本机蓝牙设备名称
  String _localDeviceName = "";

  ///蓝牙关闭时只显示2个item
  int itemCount = 2;

  /// 已绑定的蓝牙设备 {'name':'','address':''}
  List _bondedDevices = [];

  /// 点击已绑定的蓝牙设备，显示“正在连接...”
  String deviceSubtitle = "";

  List subtitles = [];



  @override
  void initState() {
    super.initState();
    SystemChrome.setEnabledSystemUIOverlays([]);
    initView();
  }

  /// 获取蓝牙状态初始化布局
  void initView() async {
    var state = await BluetoothChannel.getBluetoothState();
    String? deviceName ;
    List? list;
    if (state) {
      deviceName = await BluetoothChannel.getLocalDeviceName();
      list = await BluetoothChannel.getBondedDevices();
    }
    setState(() {
      isOpen = state;
      isOpen ? openOrClose = "开启" : openOrClose = "关闭";
      isOpen ? openOrCloseBg = Colors.blue : openOrCloseBg = Colors.grey[700];
      if (isOpen) {
        _localDeviceName = deviceName!;
        _bondedDevices = list!;
        //开启 设备名称  之前连接的设备 提示 + [已绑定的设备] 与新设备配对(x) 可被发现(x)
        itemCount = 4 + list.length;
        for (int i = 0; i < list.length; i++) {
          subtitles.add("");
        }
      }
    });
    MyLog.i("itemCount: $itemCount");
  }

  Widget _buildListItem(BuildContext context, int index) {
    if (index == 0) {
      return Container(
        color: openOrCloseBg,
        child: ListTile(
          leading: SizedBox(width: 30),
          title: Text(
            openOrClose,
            style: TextStyle(fontSize: 20, color: Colors.white),
          ),
          trailing: Switch(
            activeColor: Colors.white,
            value: isOpen,
            onChanged: (value) async {
              BluetoothChannel.openOrCloseBluetooth(value);
              String? localDeviceName;
              if (value) {
                localDeviceName = await BluetoothChannel.getLocalDeviceName();
              }
              setState(() {
                isOpen = value;
                value ? openOrClose = "开启" : openOrClose = "关闭";
                value
                    ? openOrCloseBg = Colors.blue
                    : openOrCloseBg = Colors.grey[700];
                value ? itemCount = 4 + _bondedDevices.length : itemCount = 2;
                value
                    ? _localDeviceName = localDeviceName!
                    : _localDeviceName = "";
              });
            },
          ),
          onTap: () async {
            String? localDeviceName;
            if (!isOpen) {
              localDeviceName = await BluetoothChannel.getLocalDeviceName();
            }
            setState(() {
              isOpen = !isOpen;
              isOpen ? openOrClose = "开启" : openOrClose = "关闭";
              isOpen
                  ? openOrCloseBg = Colors.blue
                  : openOrCloseBg = Colors.grey[700];
              isOpen ? itemCount = 4 + _bondedDevices.length : itemCount = 2;
              isOpen
                  ? _localDeviceName = localDeviceName!
                  : _localDeviceName = "";
            });
            BluetoothChannel.openOrCloseBluetooth(isOpen);
          },
        ),
      );
    }

    if (index == 1) {
      if (isOpen) {
        return ListTile(
          leading: SizedBox(width: 30),
          title: Text("设备名称"),
          subtitle: Text(_localDeviceName),
        );
      }
      return Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          // Divider(),
          ListTile(
            leading: Icon(Icons.info_outline),
            title: Text(
              "开启蓝牙后，您的设备可以与附近的其他蓝牙设备通信。",
              style: TextStyle(color: Colors.grey[600], fontSize: 15),
            ),
          )
        ],
      );
    }

    if (index == 2) {
      if (isOpen) {
        return ListTile(
          leading: SizedBox(width: 30),
          title: Text(
            "之前连接的设备",
            style: TextStyle(color: Colors.blue, fontSize: 12),
          ),
        );
      }
      return Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Divider(),
          ListTile(
            leading: Icon(Icons.info_outline),
            title: Text(
              "开启蓝牙后，您的设备可以与附近的其他蓝牙设备通信。",
              style: TextStyle(color: Colors.grey[600], fontSize: 15),
            ),
          )
        ],
      );
    }
    // if (index == 3) {
    //   return ListTile(
    //     leading: SizedBox(width: 30),
    //     title: Text(
    //       "之前连接的设备",
    //       style: TextStyle(color: Colors.blue, fontSize: 12),
    //     ),
    //   );
    // }
    // if (itemCount > 3 && index == itemCount - 2) {
    //   return GestureDetector(
    //     child: ListTile(
    //       leading: Icon(Icons.gps_fixed),
    //       title: Text("可被发现"),
    //       subtitle: Text("附近所有蓝牙设备均可检测到此设备"),
    //       trailing: Switch(
    //         value: couldBeFound,
    //         activeColor: Colors.blue,
    //         inactiveThumbColor: Colors.grey,
    //         onChanged: (value) {
    //           MyLog.i("couldBeFound:$value");
    //           setState(() {
    //             couldBeFound = value;
    //           });
    //         },
    //         autofocus: true,
    //       ),
    //     ),
    //     onTap: () {
    //       setState(() {
    //         couldBeFound = !couldBeFound;
    //       });
    //     },
    //   );
    // }
    if (index == itemCount - 1) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Divider(),
          ListTile(
            leading: Icon(Icons.info_outline),
            title: Text(
              "开启蓝牙后，您的设备可以与附近的其他蓝牙设备通信。",
              style: TextStyle(color: Colors.grey[600], fontSize: 15),
            ),
          )
        ],
      );
    }

    return ListTile(
      leading: Icon(Icons.bluetooth),
      title: Text(
        _bondedDevices[index - 3]["name"],
        style: TextStyle(
          color: Colors.black
        ),
      ),
      subtitle: Text(
        subtitles[index - 3],
        style: TextStyle(),
      ),
      trailing: GestureDetector(
        child: Icon(Icons.settings),
        onTap: () => Navigator.pushNamed(context, '/DeviceDetail',
            arguments: _bondedDevices[index - 3]),
      ),
      contentPadding: EdgeInsets.only(left: 17, right: 35),
      onTap: () async {
        BluetoothChannel.connectDevice(_bondedDevices[index - 3]);
        setState(() {
          subtitles[index - 3] = "正在连接中...";
        });
        Future.delayed(
            Duration(seconds: 3),
            () => setState(() {
                  subtitles[index - 3] = "";
                }));
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("蓝牙"),
        backgroundColor: Colors.black87,
        leading: BackButton(
          onPressed: () {
            Navigator.of(context).pop();
            Navigator.push(
                context, FadeRoute(IDCardRegisterPage(), seconds: 2));
          },
        ),
      ),
      body: ListView.builder(
        itemBuilder: (context, index) => _buildListItem(context, index),
        itemCount: itemCount,
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}

///蓝牙详情界面
class DeviceDetail extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Map? map = ModalRoute.of(context)!.settings.arguments as Map?;
    return Scaffold(
      appBar: AppBar(
        title: Text("设备详细信息", style: TextStyle(color: Colors.white)),
        backgroundColor: Colors.black87,
      ),
      body: ListView(
        children: [
          SizedBox(
            height: 30,
          ),
          Column(
            children: [
              Icon(
                Icons.bluetooth,
                size: 100,
                color: Colors.grey,
              ),
              Text(map!["name"])
            ],
          ),
          Divider(),
          // Row(
          //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
          //   children: [
          //     Container(
          //       alignment: Alignment.center,
          //       width: 1.sw / 2,
          //       height: 100.h,
          //       // color: Colors.yellow,
          //       child: Column(
          //         mainAxisAlignment: MainAxisAlignment.center,
          //         children: [
          //           Icon(
          //             Icons.delete,
          //             color: Colors.blue,
          //             size: 50.w,
          //           ),
          //           Text(
          //             "取消保存",
          //             style: TextStyle(fontSize: 15, color: Colors.blue),
          //           )
          //         ],
          //       ),
          //     ),
          //     Container(
          //       alignment: Alignment.center,
          //       width: 1.sw / 2,
          //       height: 100.h,
          //       child: GestureDetector(
          //         child: Column(
          //           mainAxisAlignment: MainAxisAlignment.center,
          //           children: [
          //             Icon(
          //               Icons.link,
          //               color: Colors.blue,
          //               size: 50,
          //             ),
          //             Text(
          //               "连接",
          //               style: TextStyle(fontSize: 15, color: Colors.blue),
          //             )
          //           ],
          //         ),
          //         onTap: () {
          //           MyLog.d("连接");
          //         },
          //       ),
          //     )
          //   ],
          // ),
          // Divider(),
          ListTile(
            leading: Icon(Icons.info_outline_rounded),
            title: Text("设备的蓝牙地址：${map["address"]}"),
            horizontalTitleGap: 80,
          )
        ],
      ),
    );
  }
}
